/**
 * 
 */
package com.apanal.qlife.org.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.apanal.qlife.common.constants.Constants;
import com.apanal.qlife.common.enums.AuditStatusEnum;
import com.apanal.qlife.common.page.Page;
import com.apanal.qlife.common.page.PageReturn;
import com.apanal.qlife.common.util.IdWorkerFactory;
import com.apanal.qlife.org.dao.ContractMapper;
import com.apanal.qlife.org.dao.OrganizationMapper;
import com.apanal.qlife.org.model.Contract;
import com.apanal.qlife.org.model.Organization;
import com.apanal.qlife.org.service.OrganizationService;
import com.apanal.qlife.personal.model.AuditLog;
import com.apanal.qlife.personal.service.AuditLogService;
import com.apanal.qlife.sys.model.File;
import com.apanal.qlife.sys.model.User;
import com.apanal.qlife.sys.service.FileService;
import com.apanal.qlife.sys.service.UserService;

/**
 * @author Admin
 *
 */
@Service
public class OrganizationServiceImpl implements OrganizationService {

	@Autowired
	private OrganizationMapper organizationMapper;

	@Autowired
	private ContractMapper contractMapper;

	@Autowired
	private FileService fileService;

	@Autowired
	private AuditLogService auditLogService;

	@Autowired
	private UserService userService;

	@Override
	public PageReturn<Organization> findOrganizationList(Organization organization, Page page) {
		int count = organizationMapper.findOrganizationListCount(organization);
		List<Organization> list = organizationMapper.findOrganizationList(organization, page);
		return new PageReturn<Organization>(list, count, page, organization);
	}

	public long saveOrganization(User user, Organization organization) {
		organization.setOrgId(IdWorkerFactory.nextId());
		organization.setInsertBy(user.getUseId());
		organization.setLastUpdateBy(user.getUseId());
		int organizationCount = organizationMapper.saveOrganization(organization);
		if (organizationCount > 0) {
			organization.getContract().setContractId(IdWorkerFactory.nextId());
			organization.getContract().setOrgId(organization.getOrgId());
			organization.getContract().setOrgType(organization.getOrgType());
			organization.getContract().setContractSignName(organization.getContactName());
			organization.getContract().setContractSignNumber(organization.getContactNumber());
			organization.getContract().setInsertBy(user.getUseId());
			organization.getContract().setInsertDate(organization.getInsertDate());
			organization.getContract().setLastUpdateBy(user.getUseId());
			organization.getContract().setLastUpdateDate(organization.getLastUpdateDate());
			organizationCount = contractMapper.insert(organization.getContract());
		}

		List<File> fileList = JSON.parseArray(organization.getFilelist(), File.class);
		if (fileList != null && fileList.size() > 0) {
			for (File file : fileList) {
				file.setFilId(IdWorkerFactory.nextId());
				file.setForeignId(organization.getOrgId());
				// 新增图片文件
				fileService.insertSelective(file);
			}
		}
		return organization.getOrgId();
	}

	@Override
	public PageReturn<Organization> findTrenchList(Organization organization, Page page) {
		int count = organizationMapper.findTrenchListCount(organization);
		List<Organization> list = organizationMapper.findTrenchList(organization, page);
		return new PageReturn<Organization>(list, count, page, organization);
	}

	public PageReturn<Organization> findTenementList(Organization organization, Page page) {
		int count = organizationMapper.findTenementListCount(organization);
		List<Organization> list = organizationMapper.findTenementList(organization, page);
		return new PageReturn<Organization>(list, count, page, organization);
	}

	// 待审核内容
	@Override
	public PageReturn<Organization> findAudiListNo(Organization org, Page page) {
		int count = organizationMapper.selectOrgPageCount(org, page);
		List<Organization> list = organizationMapper.selectOrgForPage(org, page);
		return new PageReturn<Organization>(list, count, page, org);
	}

	@Override
	public Organization findOrganizationById(Organization org) {

		return organizationMapper.selectByPrimaryKey(org.getOrgId());
	}

	@Override
	public Organization selectTrench(Organization org) {
		return organizationMapper.selectTrench(org.getOrgId());
	}

	@Override
	public Organization findOrganization(Long orgId, Integer orgType) {
		Organization orgz = new Organization();
		if (orgType == 1 || orgType == 2) {
			orgz = organizationMapper.selectOrgDetails(orgId);
		} else if (orgType == 3) {
			orgz = organizationMapper.selectOrgDetails1(orgId);

		}
		return orgz;
	}

	public List<Organization> findOrgList(Organization organization) {
		return organizationMapper.findOrgList(organization);
	}

	public Organization selectByPrimaryKey(Organization organization) {
		return organizationMapper.selectByPrimaryKey(organization.getOrgId());
	}

	// 根据当前登录人找到其所对应的关系
	@Override
	public Organization findPaltByUser(Long useId) {
		return organizationMapper.findPlatByUser(useId);
	}

	/**
	 * 禁用启用
	 * 
	 * @param organization
	 * @return
	 */
	public Integer updateByAuditStatus(Organization organization) {
		Integer count = organizationMapper.update(organization);

		try {
			// 机构停用时,为该机构下直属且已登录的用户设置停用标注(仅机构停用时调用)
			if (Constants.NORMAL_FALSE.equals(organization.getNormal())) {
				userService.setLoginUserOrgDisableFlag(organization.getOrgId());
			}
		} catch (Exception e) {
			// 不处理
		}

		return count;
	}

	public Integer update(User user, Organization organization) {
		int organizationCount = 0;
		organization.setLastUpdateBy(user.getUseId());
		if (organization.getCopyOrgId() == null) {
			organizationCount = organizationMapper.update(organization);
			if (organizationCount == 1 && organization.getContract().getContractId() > 0) {
				organization.getContract().setOrgId(organization.getOrgId());
				organization.getContract().setOrgType(organization.getOrgType());
				organization.getContract().setContractSignName(organization.getContactName());
				organization.getContract().setContractSignNumber(organization.getContactNumber());
				organization.getContract().setInsertBy(organization.getInsertBy());
				organization.getContract().setInsertDate(organization.getInsertDate());
				organization.getContract().setLastUpdateBy(organization.getLastUpdateBy());
				organization.getContract().setLastUpdateDate(organization.getLastUpdateDate());
				organizationCount = contractMapper.updateContract(organization.getContract());
			}
			List<File> fileList = new ArrayList<File>();
			if (organization.getFilelist().isEmpty() && organization.getFilelist() != null) {
				fileList = JSON.parseArray(organization.getFilelist(), File.class);
				if (organizationCount == 1 && fileList != null && fileList.size() > 0) {
					for (File file : fileList) {
						file.setForeignId(organization.getOrgId());
						// 新增图片文件
						fileService.insertSelective(file);
					}
				}
			}
		} else {
			organization.setCopyOrgId(organization.getOrgId());
			organization.setOrgId(IdWorkerFactory.nextId());
			organizationCount = organizationMapper.saveOrganization(organization);
			if (organizationCount > 0) {
				organization.getContract().setContractId(IdWorkerFactory.nextId());
				organization.getContract().setOrgId(organization.getOrgId());
				organization.getContract().setOrgType(organization.getOrgType());
				organization.getContract().setContractSignName(organization.getContactName());
				organization.getContract().setContractSignNumber(organization.getContactNumber());
				organization.getContract().setInsertBy(organization.getInsertBy());
				organization.getContract().setInsertDate(organization.getInsertDate());
				organization.getContract().setLastUpdateBy(organization.getLastUpdateBy());
				organization.getContract().setLastUpdateDate(organization.getLastUpdateDate());
				organizationCount = contractMapper.insert(organization.getContract());
			}

			List<File> fileList = new ArrayList<File>();
			if (organization.getFilelist().isEmpty() && organization.getFilelist() != null) {
				fileList = JSON.parseArray(organization.getFilelist(), File.class);
				if (fileList != null && fileList.size() > 0) {
					for (File file : fileList) {
						file.setForeignId(organization.getOrgId());
						// 新增图片文件
						fileService.insertSelective(file);
					}
				}
			}

			// File f= new File();
			// f.setForeignId(organization.getCopyOrgId());
			// fileList = fileService.selectRelation(f);
			// update by shuliangxing
			fileList = fileService.select(Constants.CORP_IMG, organization.getCopyOrgId());// 这里有些问题麻烦修改下

			if (fileList != null && fileList.size() > 0) {
				for (File file : fileList) {
					file.setFilId(IdWorkerFactory.nextId());
					file.setForeignId(organization.getOrgId());
					// 新增图片文件
					fileService.insertSelective(file);
				}
			}
		}
		return organizationCount;
	}

	public List<Organization> findAllPlat() {

		return organizationMapper.findAllPlat();
	}

	@Override
	public PageReturn<Organization> selectRelationForPage(Organization org, Page page) {
		int count = organizationMapper.selectRelationForPageCount(org, page);
		List<Organization> list = organizationMapper.selectRelationForPage(org, page);
		return new PageReturn<Organization>(list, count, page, org);
	}

	@Override
	public List<Organization> selectByIds(String ids) {
		if (ids == null || "".equals(ids)) {
			return null;
		} else {
			Organization param = new Organization();
			param.setOrgids(ids);
			return organizationMapper.select(param);
		}
	}

	@Override
	public List<Organization> findAllQd() {
		return organizationMapper.findAllQd();
	}

	@Override
	public Organization selectOrganizationById(Organization org) {
		return organizationMapper.selectOrgById(org.getOrgId());
	}

	@Override
	public String updateOrg(Organization orgz, User user, Organization org) {
		int AudPreStatus = orgz.getAuditStatus();
		if (orgz.getCopyOrgId() != null) {
			if (AuditStatusEnum.AGREE.getValue() == org.getAgreeStatus()) {
				orgz.setAuditStatus(AuditStatusEnum.REJECT.getValue());
				orgz.setLastUpdateBy(user.getUseId());
				organizationMapper.update(orgz);
			} else if (AuditStatusEnum.AGREE.getValue() == org.getAgreeStatus()) {
				orgz.setAuditStatus(AuditStatusEnum.AGREE.getValue());

				Organization enty = new Organization();
				enty.setOrgId(orgz.getCopyOrgId());
				Organization oz = selectOrganizationById(enty); // 原始记录
				oz.setAuditStatus(AuditStatusEnum.AGREE.getValue());
				oz.setOrgType(orgz.getOrgType());
				oz.setOrgName(orgz.getOrgName());
				oz.setComRegName(orgz.getComRegName());
				oz.setOrgPId(orgz.getOrgPId());
				oz.setOrgPIds(orgz.getOrgPIds());
				oz.setProvinceId(orgz.getProvinceId());
				oz.setCityId(orgz.getCityId());
				oz.setAreaId(orgz.getAreaId());
				oz.setAddress(orgz.getAddress());
				oz.setCorpName(orgz.getCorpName());
				oz.setCorpIdCardNumber(orgz.getCorpIdCardNumber());
				oz.setCorpIdCareEndDate(orgz.getCorpIdCareEndDate());
				oz.setBusinessLicenseNumber(orgz.getBusinessLicenseNumber());
				oz.setBusinessLicenseEndDate(orgz.getBusinessLicenseEndDate());
				oz.setOrgNumber(orgz.getOrgNumber());
				oz.setOrgEndDate(orgz.getOrgEndDate());
				oz.setTaxRegCertifNumber(orgz.getTaxRegCertifNumber());
				oz.setTaxRegCertifEndDate(orgz.getTaxRegCertifEndDate());
				oz.setServiceHotline(orgz.getServiceHotline());
				oz.setOrgIcon(orgz.getOrgIcon());
				oz.setContactName(orgz.getContactName());
				oz.setContactNumber(orgz.getContactNumber());
				oz.setNormal(orgz.getNormal());
				oz.setStatus(orgz.getStatus());
				oz.setInsertBy(orgz.getInsertBy());
				oz.setLastUpdateBy(user.getUseId());
				organizationMapper.update(oz);
				// 更新合同表
				Long contractId = oz.getContract().getContractId();
				Long oldId = oz.getContract().getOrgId();
				Contract newContract = orgz.getContract();
				contractMapper.deleteByPrimaryKey(contractId);
				newContract.setOrgId(oldId);
				contractMapper.updateContract(newContract);
				// 更新file表
				List<File> list = orgz.getFileLists();
				fileService.deleteByForeignId(orgz.getCopyOrgId());
				for (File f : list) {
					f.setFilId(IdWorkerFactory.nextId());
					f.setForeignId(orgz.getCopyOrgId());
					f.setNormal(Constants.NORMAL_TRUE);
					f.setStatus(Constants.IS_VALID_TRUE);
					// f.setStatus(Constants.)
					fileService.insert(f);
				}
				deleteOrg(orgz.getOrgId());
			}
		} else {
			if (org.getAgreeStatus() == -1) {
				orgz.setAuditStatus(AuditStatusEnum.REJECT.getValue());
			} else if (org.getAgreeStatus() == 2) {
				orgz.setAuditStatus(AuditStatusEnum.AGREE.getValue());
			}
			orgz.setLastUpdateBy(user.getUseId());
			organizationMapper.update(orgz);
			// 更新合同表 todo
			contractMapper.updateContract(orgz.getContract());
		}
		// 插入审核表记录
		AuditLog alog = new AuditLog();
		alog.setAudAdvices(org.getAudAdvices());
		alog.setAudType(Constants.AUDIT_TYPE_ORG);
		alog.setAudPreStatus(AudPreStatus);
		alog.setAudSufStatus(orgz.getAuditStatus());
		alog.setForeignId(orgz.getOrgId());
		alog.setInsertBy(user.getUseId());
		alog.setAudId(IdWorkerFactory.nextId());
		auditLogService.insertAuditLog(alog);
		return Constants.DEFAULT_MSG_SUCCESS;
	}

	@Override
	public PageReturn<Organization> findAudiList(Organization org, Page page) {
		int count = organizationMapper.selectOrgAutditPageCount(org, page);
		List<Organization> list = organizationMapper.selectOrgAutditForPage(org, page);
		return new PageReturn<Organization>(list, count, page, org);
	}

	@Override
	public String deleteOrg(Long orgId) {
		organizationMapper.deleteByPrimaryKey(orgId);
		contractMapper.deleteByOrgId(orgId);
		return Constants.DEFAULT_MSG_SUCCESS;
	}

	/**
	 * 根据当前登录用户获取待审核总条数的接口
	 * 
	 * @param user
	 * @return
	 */
	@Override
	public Integer selectCountAudit() {
		Organization org = new Organization();
		User user = userService.getCurrentUser();
		org.setOrgId(user.getOrgId());
		Organization orgz = findOrganizationById(org);
		String orgPIds = orgz.getOrgPIds() + orgz.getOrgId().toString();
		org.setOrgPIds(orgPIds);
		int total = organizationMapper.selectCountAudit(org);
		return total;
	}
}
